package com.t235.gc.configs.service;

import com.t235.gc.configs.config.CookieUtil;
import com.t235.gc.entity.SysManager;
import com.t235.gc.entity.SysMenu;
import com.t235.gc.entity.SysRole;
import com.t235.gc.mapper.SysManagerMapper;
import com.t235.gc.mapper.SysMenuMapper;
import com.t235.gc.mapper.SysRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    SysManagerMapper sysManagerMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String Username) throws UsernameNotFoundException {

        //CookieUtil.addCookie("SESSION");
        //登入时访问该方法
        //方法参数是用户登入时的账号
        //1.首先获取数据库中的该用户名的信息
        System.out.println(Username);
        SysManager user = sysManagerMapper.FindByUsername(Username);
        if(user==null){
            throw new UsernameNotFoundException("账号不存在");
        }
        /*//2.2如果存在该用户，看其是否被审核通过了
        if (user.getIsflag().equals("1")){
            throw new UsernameNotFoundException("账号被禁用了");
        }*/
        //2 当审核通过时，查看密码是否正确
        String password = user.getPassword();

        user.setRoles(sysRoleMapper.FindByUserId(user.getManagerid()));//根据用户id查询角色信息表
        List<SysRole> roles = user.getRoles();
        if(roles!=null){
            //根据角色Id查询对应的菜单
            roles.forEach(num -> {
                System.out.println(num.getRolename());
                List<SysMenu> menus = sysMenuMapper.FindByRoleId(num.getId());
                num.setMenus(menus);
            });
        }

        return user;
    }
}
